<?php
namespace app\admin\model;
use think\Model;
use think\Db;
use think\facade\Config;
class ModelsField extends  Model
{
	public function addModel($data)
	{
	    if (empty($data)) {
	        return false;
	    }
	    //添加模型字段和修改表字段
		
		$ndata = [
			"ename"=>$data['ename'],
			"cname"=>$data['cname'],
			"type"=>$data['type'],
			"descript"=>$data['descript'],
			"validate"=>$data['validate'],
			"sort"=>$data['sort'],
			"model_id"=>$data['model_id'],
			"show"=> 1,
			"addendum" =>$data['table'],
			"isedit"=> 1
		];
		if(isset($data['value'])){
			$ndata['value'] = $data['value'];
		}
		$id = $this->creatField($ndata);
	    if ($id) {
	        $this->editTable($data);
	        return true;
	    }
	    return false;
	}
	
	//新增模型字段记录对应表模型
	public function creatField($data){
		 return $this->insertGetId($data);
	}
	//修改对应表结构
	public function editTable($data){
		$res = Db::name('models')->where(['id'=>$data['model_id']])->find();
		
		$type = Db::name('field_type')->where(['id'=>$data['type']])->find();
		if($data['table'] == 1){
			$tablename =config('database.prefix') . $res['table_name'];
			//先将字段存在设置的主表
			$sql = <<<EOF
				ALTER TABLE `{$tablename}` ADD COLUMN `{$data['ename']}` {$type['default_define']} COMMENT '{$data['descript']}';
EOF;
		}else{
			$tablename = config('database.prefix') . $res['table_name']."_data";
			//先将字段存在设置的附表里面
			$sql = <<<EOF
				ALTER TABLE `{$tablename}` ADD COLUMN `{$data['ename']}` {$type['default_define']} COMMENT '{$data['descript']}';
EOF;
		}
		
		try {
			$res = Db::execute($sql);
		} catch (\Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	/**
	     * 删除字段
	     * @param type $data 字段id
	     * @return boolean
	     */
	    public function deleteField($data)
	    {
	
	        //原字段信息
	        $info = self::where(["id" => $data['id']])->find();
	        if (empty($info)) {
	            $this->error = '该字段不存在！';
	            return false;
	        }
			self::get($data['id'])->delete();
	        //完整表名获取 判断主表 还是副表
	        $res = Db::name('models')->where(['id'=>$data['model_id']])->find();
	        if (!$this->table_exists($res['table_name'])) {
	            $this->error = '数据表不存在！';
	            return false;
	        }
	        
			if($info['addendum'] == 1){
				$tablename = config('database.prefix') . $res['table_name'];
			}else{
				$tablename = config('database.prefix') . $res['table_name'] . "_data";
			}
	        //判断是否允许删除
	        $sql = <<<EOF
			ALTER TABLE `{$tablename}`
			DROP COLUMN `{$info['ename']}`;
EOF;
		try {
			$res = Db::execute($sql);
		} catch (\Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
		
		return true;
	}
	
	public function editField($data){
		$ndata = [
			'cname' => $data['cname'],
			'descript' => $data['descript'],
			'validate' => $data['validate'],
			'sort' => $data['sort']
		];
		$this->where(['id'=>$data['id']])->update($ndata);
		return true;
	}
	
	/**
	 * 检查表是否存在
	 * $table 不带表前缀
	 */
	public function table_exists($table)
	{
	    $table = Config::get("database.prefix") . strtolower($table);
	    if (true == Db::query("SHOW TABLES LIKE '{$table}'")) {
	        return true;
	    } else {
	        return false;
	    }
	}
	
	
}